<template>
  <div>
    <el-space direction="vertical" class="content">
      <el-card class="box-card">
        <p class="p-title">商品(Spu)介绍</p>
        <el-form
          class="form"
          :model="form"
          ref="ruleFormRef"
          :rules="rules"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="原始价格" prop="originalPrice">
            <el-input v-model="form.originalPrice" placeholder="0" clearable>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="当前价格" prop="price">
            <el-input v-model="form.price" placeholder="0" clearable>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="VIP价格" prop="vipPrice">
            <el-input v-model="form.vipPrice" placeholder="0" clearable>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="剩余库存">
            <el-input v-model="form.stock" placeholder="0" disabled />
          </el-form-item>
          <el-form-item label="运费模板" prop="type">
            <el-cascader
              v-model="form.freightTemplateId"
              :options="FreightOptions"
              placeholder="请选择商品运费模板"
              :props="yunfeiprops"
            />
          </el-form-item>
          <el-form-item label="是否在售" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">在售</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              :action="action"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
               list-type="picture-card"
              :headers="headers"
            >
              <img v-if="form.imgList" :src="form.imgList"  />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位" prop>
            <el-input v-model="form.unit" placeholder="件/个/盒" />
          </el-form-item>
          <el-form-item label="所属类目">
            <el-cascader
              v-model="form.categoryId"
              :options="options"
              placeholder="优惠类目"
              :props="cateprops"
            />
          </el-form-item>
          <el-form-item label="商品简介" prop>
            <el-input v-model="form.description" />
          </el-form-item>
          <el-form-item label="商品详细介绍" prop>
            <!-- 富文本 -->
            <tinymce v-model="form.detail" />
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card" style="width: 250px">
        <p class="p-title">商品参数</p>
        <el-button @click="comParaAdd" type="primary" plain>添加</el-button>
        <!-- 列表 -->
        <el-table :data="form.attributeList" style="width: 100%" border>
          <el-table-column prop="attribute" label="商品参数名称" align="center" />
          <el-table-column prop="value" label="商品参数值" align="center" />
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="box-card" style="width: 250px">
        <p class="p-title">商品规格</p>
        <el-button @click="guigeAdd" type="primary" plain>添加</el-button>
        <!-- 列表 -->
        <el-table :data="form.specificationList" style="width: 100%" border>
          <el-table-column prop="id" label="维度ID" align="center" />
          <el-table-column prop="title" label="维度名称" align="center" />
          <el-table-column prop="gmtCreate" label="创建时间" align="center">
            <template #default="scope">{{scope.row.gmtCreate?formatD(scope.row.gmtCreate):''}}</template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 修改弹框1 -->
      <el-dialog v-model="dialogFormVisiblePara" :title="dialogTitle">
        <el-form
          class="form"
          :model="formPara"
          ref="ruleFormRefPara"
          :rules="rulesPara"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="商品参数名称" prop="name">
            <el-input v-model="formPara.name" />
          </el-form-item>
          <el-form-item label="商品参数值" prop="paraval">
            <el-input v-model="formPara.paraval" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisiblePara=false">取消</el-button>
            <el-button type="primary" @click="fangdou">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 修改弹框2 -->
      <el-dialog v-model="dialogFormVisibleRule" title="创建规格">
        <el-form
          class="form"
          :model="formRule"
          ref="ruleFormRefRule"
          :rules="rulesRule"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="类型名称" prop="typename">
            <el-input v-model="formRule.typename" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisibleRule=false">取消</el-button>
            <el-button type="primary" @click="fangdouRule" @blur="blur">创建规格</el-button>
          </span>
        </template>
      </el-dialog>
      <el-card class="box-card" style="width: 250px">
        <template #header>
          <div class="card-header">
            <p class="p-title">商品(sku)详情</p>
            <el-button @click="batchPricing" type="primary" plain>批量定价</el-button>
          </div>
        </template>
        <!-- 规格值 -->
        <el-space
          style="display: block;"
          direction="vertical"
          v-for="(tag,index) in form.specificationList"
          :key="index"
        >
          <div>
            <el-tag type="warning">{{ tag.title }}</el-tag>
            <el-tag
              v-for="(tagSun,ind) in tag.values"
              :key="ind"
              closable
              :disable-transitions="false"
              @close="handleClose(index,tagSun)"
            >{{ tagSun }}</el-tag>
            <el-input
              style="width:100px"
              v-if="tag.inputSkuTagVisible"
              :ref="'input'+index"
              v-model="tag.inputSkuTagValue"
              size="small"
              @keyup.enter="handleInputConfirm(tag.inputSkuTagValue,index)"
              @blur="handleInputConfirm(tag.inputSkuTagValue,index)"
            />
            <el-button v-else size="small" @click="showInput(index)">添加</el-button>
          </div>
        </el-space>

        <!-- 列表 -->
        <el-table :data="form.skuList" style="width: 100%" :span-method="tableSpanMethod" border>
          <el-table-column
            :prop="'id_'+tag.title"
            :label="tag.title"
            align="center"
            v-for="(tag,index) in form.specificationList"
            :key="index"
          ></el-table-column>
          <el-table-column prop="name" label="Skuid" align="center" />
          <el-table-column prop="originalPrice" label="￥物价(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.originalPrice" :min="1" placeholder="0" />
            </template>
          </el-table-column>
          <el-table-column prop="vipPrice" label="￥VIP价(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.vipPrice" :min="1" placeholder="0" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="￥吊牌价(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.price" :min="1" placeholder="0" />
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.stock" :min="0" placeholder="0" />
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.weight" :min="0" placeholder="0" />
            </template>
          </el-table-column>
          <el-table-column prop="img" label="sku图片" align="center">
            <template #default="scope">
              <el-upload
                class="avatar-uploader"
                style="width:80px;height:80px;margin:auto"
                :action="action"
                :on-success="handleAvatarSuccessTable"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false"
                :headers="headers"
                @click="changeimg(scope.$index)"
              >
                <canvas v-show="false" id="canvas" />
                <img v-if="scope.row.img" :src="scope.row.img" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Upload />
                </el-icon>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" label="条形码" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.barCode">
                <template #append>
                  <el-button size="small" type="danger" @click="scope.row.barCode=+new Date()">随机数</el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 修改弹框3 -->
      <el-dialog v-model="dialogFormVisibleBatch" title="批量定价">
        <el-form class="form" :model="formBatch" label-width="120px" label-position="left">
          <el-form-item label="现价(￥)" prop="typename">
            <el-input-number v-model="formBatch.originalPrice" :min="1" placeholder="0" />
          </el-form-item>
          <el-form-item label="VIP现价(￥)" prop="typename">
            <el-input-number v-model="formBatch.vipPrice" :min="1" placeholder="0" />
          </el-form-item>
          <el-form-item label="吊牌价(￥)" prop="typename">
            <el-input-number v-model="formBatch.price" :min="1" placeholder="0" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisibleBatch=false">取消</el-button>
            <el-button type="primary" @click="fangdouBatch">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <div class="footstep">
      <div class="butt">
          <el-button>取消</el-button>
        <el-button type="primary" @click="saveGoods('ruleFormRef')">保存商品</el-button>
      </div>
      </div>
    </el-space>
  </div>
</template>
<script>
import { post, action } from "@/util/http";
import Cookies from "js-cookie";
import { Plus, Upload } from "@element-plus/icons-vue";
import tinymce from "../../../../components/richtext/RichText.vue";
import { ElMessage } from "element-plus";
import formatD from "../../../../timeformat/formatD";
import { debounce } from "@/fangdou/fangdou"; //防抖fangdou
export default {
  components: {
    Plus,
    Upload,
    tinymce,
  },
  data() {
    return {
      action,
      options: [],
      // 富文本的配置
      init: {
        selector: "#tinydemo", //容器，可使用css选择器
        // language: "zh_CN", //调用放在langs文件夹内的语言包
        toolbar: false, //隐藏工具栏
        menubar: false, //隐藏菜单栏
        inline: true, //开启内联模式
        plugins: ["quickbars", "link", "table"], //选择需加载的插件
        //选中时出现的快捷工具，与插件有依赖关系
        quickbars_selection_toolbar:
          "bold italic forecolor | link blockquote quickimage",
      },
      // 运费模板
      FreightOptions: [],
      //运费选择器数据配置
      yunfeiprops: {
        value: "id",
        label: "title",
        children: "carriageDOList",
        emitPath: false,
      },
      // 类目选择器数据配置
      cateprops: {
        value: "id",
        label: "title",
        children: "childrenList",
        emitPath: false,
      },
      // 表单数据
      form: {
        title: "",
        price: "", //当前价钱
        originalPrice: "", //原始价钱
        vipPrice: "", //vip价格
        stock: "", //库存
        freightTemplateId: "", //运费模板
        status: 1, //是否在售
        imgList: [], //商品图片
        unit: "", //商品单位
        categoryId: "", //所属类目
        description: "", //商品简介
        detail: "", //商品详情介绍
        specificationList: [],
        attributeList: [], //商品参数表格数据
        skuList: [],
        img:"",
      },
      //  图片请求头
      headers: { AdminToken: Cookies.get("token") },
      imgIndex: "", //表格上传图片的下标
      // 商品参数添加弹框的布尔值
      dialogFormVisiblePara: false,
      dialogFormVisibleRule: false, //弹框2的布尔值
      dialogFormVisibleBatch: false, //弹框3的布尔值
      dialogTitle: "", //弹框标题
      // 弹框1数据
      formPara: {
        name: "",
        paraval: "",
      },
      // 弹框2数据
      formRule: {
        typename: "",
      },
      // 弹框3数据
      formBatch: {
        price: "", //当前价钱
        originalPrice: "", //原始价钱
        vipPrice: "", //vip价格
      },
      // 表单规则
      rules: {
        title: [
          {
            required: true,
            message: "请输入商品标题",
            trigger: "blur",
          },
        ],
        skuGroupShopPrice: [
          {
            required: true,
            message: "请输入原始价格",
            trigger: "blur",
          },
        ],
        originalPrice: [
          {
            required: true,
            message: "请输入当前价格",
            trigger: "blur",
          },
        ],
        vipPrice: [
          {
            required: true,
            message: "请输入当前价格",
            trigger: "blur",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: "blur",
          },
        ],
      },
      // 商品参数的rule
      rulesPara: {
        name: [
          {
            required: true,
            message: "请输入商品参数名称",
            trigger: "blur",
          },
        ],
        paraval: [
          {
            required: true,
            message: "请输入商品参数值",
            trigger: "blur",
          },
        ],
      },
      // 规格的rule
      rulesRule: {
        typename: [
          {
            required: true,
            message: "请输入类型名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // 运费模板
    this.freight();
    // 类目树
    this.productTree();
  },
  methods: {
    formatD, //时间格式转换
    // 保存商品
    saveGoods() {
            let data = {
        _gp: "admin.product",
        _mt: "create",
        spuDTO:JSON.stringify(this.form)
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          console.log("商品创建成功");
          ElMessage.success("商品创建成功")
        }
      });
    },
    showInput(index) {
      this.form.specificationList[index].inputSkuTagVisible = true; //添加当前规格值的布尔值为true
      //添加的表前出现
      this.$nextTick(() => {
        this.$refs["input" + index][0].focus(); //聚焦
        // this.$refs.InputRef[0]?.focus();//聚焦
      });
    },
    handleInputConfirm(inputSkuTagValue, index) {
      if (this.form.specificationList[index].values.length>0&&this.form.specificationList[index].values.find(item=>item==inputSkuTagValue)) {
        return ElMessage.warning("该规格值已存在!")
      }
      //失去焦点事件
      if (inputSkuTagValue) {
        //如果输入框有值
        this.form.specificationList[index].values.push(inputSkuTagValue); //就追加到当前的values中
      }
      this.form.specificationList[index].inputSkuTagVisible = false; //当前规格值的布尔值为false
      this.form.specificationList[index].inputSkuTagValue = ""; //清空输入框
      this.createdList(); //调用笛卡尔处理数据的事件
    },
    handleClose(index, ind) {
      let value = this.form.specificationList[index].values;
      value.splice(value.indexOf(ind), 1); //叉掉规格值
      // this.createdList();
    },
    // 批量定价
    batchPricing() {
       let list = this.form.skuList
       list.forEach((item) => {
        this.formBatch.price=item.price
        this.formBatch.vipPrice=item.vipPrice
        this.formBatch.originalPrice=item.originalPrice
      });
      this.dialogFormVisibleBatch = true;
    },
    // 商品参数弹框的确定按钮--提交
    subMitBatch() {
      let list = this.form.skuList
       list.forEach((item) => {
        item.price=this.formBatch.price
        item.vipPrice=this.formBatch.vipPrice
        item.originalPrice=this.formBatch.originalPrice
      });
       this.dialogFormVisibleBatch = false;
    },
    fangdouBatch: debounce(function () {
      //防抖
      this.subMitBatch();
    }),
    // 商品参数添加
    comParaAdd() {
      Object.assign(this.formPara, {
        typename: "",
      });
      this.dialogFormVisiblePara = true;
      this.dialogTitle = "设置商品参数";
    },
    // 规格维度添加
    guigeAdd() {
      Object.assign(this.formPara, {
        name: "",
        paraval: "",
      });
      this.dialogFormVisibleRule = true;
      this.dialogTitle = "创建规格";
    },
    // 商品参数弹框的确定按钮--提交
    subMit() {
      if (this.form.attributeList.find((item) => item.attribute == this.formPara.name))
        return ElMessage.warning("该参数已存在!");

      this.$refs.ruleFormRefPara.validate((valid) => {
        if (valid) {
          this.form.attributeList.push({
            attribute: this.formPara.name,
            value: this.formPara.paraval,
          });
          this.dialogFormVisiblePara = false;
          Object.assign(this.formPara, {
            name: "",
            paraval: "",
          });
        }
      });
    },
    fangdou: debounce(function () {
      //防抖
      this.subMit();
    }),
    // 规格维度弹框的确定按钮--提交
    subMitRule() {
      //如果数组查找出有该值了就返回一个警告
      if (
        this.form.specificationList.find(
          (item) => item.title == this.formRule.typename
        )
      )
        return ElMessage.warning("该规格已存在!");
      this.$refs.ruleFormRefRule.validate((ref) => {
        if (ref) {
          this.form.specificationList.push({
            //追加
            title: this.formRule.typename,
            values: [],
            inputSkuTagVisible: false,
            gmtCreate: +new Date(),
            inputSkuTagValue: "", //要输入添加规格值的输入框绑定值
          });
          this.dialogFormVisibleRule = false; //弹框隐藏
          this.formRule.typename = ""; //清空输入框
          this.createdList(); //调用表格数据处理事件
        }
      });
    },
    fangdouRule: debounce(function () {
      //防抖
      this.subMitRule();
    }),
    // 笛卡尔算法
    createdList() {
      let specificationList = this.form.specificationList;
      let title = specificationList.map((item) => {
        //映射出标题
        return item.title;
      });
      // 规格值
      let valuelist = specificationList
        .map((item) => {
          //映射
          return item.values;
        })
        .filter((item) => {
          //过滤
          return item.length > 0;
        });
      let list = valuelist.reduce(
        //笛卡尔算法
        (total, next) => {
          let array = [];
          total.forEach((item) => {
            next.forEach((item2) => {
              array.push(item.concat(item2)); //合并数组
            });
          });
          return array;
        },
        [[]]
      );
      let { vipPrice, price, originalPrice } = this.form; //价格
      let arr = list.map((item) => {
        //映射全部规格值
        let obj = {
          title: [],
          originalPrice,
          price,
          vipPrice,
          stock: 0,
          specification: [], //规格维度
          weight: "",
          barCode: "",
          img: "",
        };
        item.forEach((ite, index) => {
          let key = "id_" + title[index];
          obj[key] = ite;
          obj.title.push(ite);
          obj.specification.push(title[index] + "_" + ite); //追加id_尺寸、id_颜色
        });
        obj.title = obj.title.join(); //转换成字符串
        obj.specification = obj.specification.join();
        return obj; //重新返回一个对象
      });
      this.form.skuList = arr; //重新赋值数组
    },
    // 跨行
    tableSpanMethod({ rowIndex, columnIndex }) {
            let specList = this.form.specificationList.filter(item => item.values.length > 0)//获取规格列表
      if(!specList.length)return this.form.skuList = []
      if (columnIndex < specList.length - 1) {//对要跨行的列进行计算，排除最后一个属性列(最后一个属性列不存在跨行)
        let rowSpanNum = 1
        for (let i = columnIndex + 1; i < specList.length; i++) {
          rowSpanNum *= specList[i].values.length//跨行的数量=后面属性值数量的乘积
        }
        if (rowIndex % rowSpanNum === 0) {
          return { rowspan: rowSpanNum, colspan: 1 }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      }
    },
    // 类目树请求
    productTree() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      post(data).then((res) => {
        this.options = res.data.data;
      });
    },
    // 运费模板
    freight() {
      let data = {
        _gp: "admin.freight",
        _mt: "list",
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.FreightOptions = res.data.data;
        }
      });
    },
    // 类目列表
    categoryData() {
      let data = {
        _gp: "admin.product",
        _mt: "getSpuBigTree",
      };
      post(data).then((res) => {
        if (200 == res.data.errno) {
          this.options = res.data.data;
        }
      });
    },
    // 成功上传图片---处理化身成功
    handleAvatarSuccess(res, file) {
      let { errno, url } = res;
      if (200 == errno) {
        console.log(url, "我要的图片路径");
        this.$nextTick(() => {
          this.form.imgList.push(url);
          this.form.img=url
        });
      } else {
        ElMessage.warning("图片上传失败");
      }
    },
    // 表格成功上传图片---处理化身成功
    handleAvatarSuccessTable(res, file) {
      let { errno, url } = res;
      if (200 == errno) {
        this.$nextTick(() => {
          this.form.skuList[this.imgIndex].img = url;
        });
      }
    },
    changeimg(i) {
      this.imgIndex = i; //表格当前行的上传图片下标
    },
    // 上传之前
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== "image/jpeg") {
        ElMessage.error("图片格式必须是jpeg!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("文件大小不能超过2MB!");
        return false;
      }
      return true;
    },
  },
};
</script>
<style lang="less" scoped>
.content {
  display: block;
}
// 表单的上传图片
.avatar-uploader {
  width: 178px;
  height: 178px;
}
.avatar-uploader /deep/ .el-upload {
  width: 100%;
  height: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 100%;
}
//主题
.p-title {
  font-weight: 700;
}
.form {
  margin-left: 70px;
}
// 表格上面的规格标签
.card-conter {
  white-space: nowrap;
}
.tag-head {
  margin-bottom: 10px;
}
.tags-input {
  width: auto;
  margin-left: 10px;
}
.tag-con {
  margin-left: 10px;
}
.butt{//底部按钮
  float: right;
}
</style>